<template>
  <el-card class="page-title-container" style="height: 60px">
    <h2 class="page-title">修改密码</h2>
  </el-card>
  <div class="user-info-container">
    <div class="password-content">
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="120px"
        class="password-form"
      >
        <el-form-item label="原密码" prop="pass">
          <el-input
            v-model="passwordForm.pass"
            type="password"
            show-password
            placeholder="请输入原密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="onenewpass">
          <el-input
            v-model="passwordForm.onenewpass"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="newPass">
          <el-input
            v-model="passwordForm.newPass"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleChangePassword">确认修改</el-button>
          <el-button @click="handleResetPassword">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
/**
 * 个人信息页面组件
 * 功能：显示和编辑用户基本信息，修改密码
 */

import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import { useRouter, useRoute } from 'vue-router'
import myaxios from '@/Http/http'

// ==================== 初始化 ====================
const store = useCounterStore() // Pinia store 实例
const route = useRoute()

// ==================== 数据定义 ====================

/**
 * 修改密码表单数据
 */
const passwordForm = reactive({
  id: store.userinfo.userid,
  pass: '',
  onenewpass: '',
  newPass: '',
})

/**
 * 密码表单引用
 */
const passwordFormRef = ref<FormInstance>()

/**
 * 密码表单验证规则
 */
const passwordRules = reactive<FormRules>({
  pass: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  onenewpass: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  newPass: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPass) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

// ==================== 生命周期 ====================

/**
 * 组件挂载时加载用户信息
 */
onMounted(() => {})

// ==================== 方法定义 ====================

/**
 * 保存密码到 Pinia store
 * 使用 base64 编码对密码进行简单加密存储
 * @param {string} username - 用户名
 * @param {string} password - 用户密码（明文）
 */
const savePassword = (password: string) => {
  try {
    // 使用 base64 编码对密码进行加密（注意：base64 不是真正的加密，只是编码）
    const encodedPassword = btoa(unescape(encodeURIComponent(password)))
    // 将用户名、加密后的密码和记住密码标志保存到 store
    store.userinfo.userpass = encodedPassword
    store.userinfo.passstate = true
  } catch (error) {
    console.error('保存密码失败:', error)
  }
}

/**
 * 从 Pinia store 读取保存的用户名和密码
 * 如果之前勾选了记住密码，则自动填充表单
 */
const userPass = reactive({
  pass: '',
  passstate: false,
})

const loadPassword = () => {
  try {
    // 从 store 中获取保存的用户名、密码和记住密码标志
    const rememberedPassword = store.userinfo.userpass
    const rememberFlag = store.userinfo.passstate

    // 如果存在保存的用户名和密码，且记住密码标志为 true
    if (rememberedPassword && rememberFlag === true) {
      // base64 解码，还原密码
      const decodedPassword = decodeURIComponent(escape(atob(rememberedPassword)))
      userPass.pass = decodedPassword
      // 自动勾选记住密码复选框
      userPass.passstate = true
    }
  } catch (error) {
    console.error('读取密码失败:', error)
    // 如果读取失败，清除保存的数据，避免数据损坏
  }
}

/**
 * 修改密码
 */
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  loadPassword()
  // 表单验证
  await passwordFormRef.value.validate((valid, fields) => {
    if (valid) {
      // TODO: 调用 API 修改密码
      myaxios.post('/api/Users/UpdateUserPass', passwordForm).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message)
          if (userPass.passstate == true) {
            savePassword(passwordForm.newPass)
          }
          // 清空表单
          handleResetPassword()
        } else {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('表单验证失败:', fields)
    }
  })
}

/**
 * 重置密码表单
 */
const handleResetPassword = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  passwordForm.pass = ''
  passwordForm.onenewpass = ''
  passwordForm.newPass = ''
}
</script>

<style scoped>
/**
 * ==================== 个人信息页面样式 ====================
 */

/* 容器样式 */
.user-info-container {
  padding: 0;
  background: #fff;
  /* min-height: calc(100vh - 60px); 减去 header 高度 */
  box-sizing: border-box;
  width: 100%;
  height: 300px;
}

/* 页面标题 */
.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  /* padding: 24px 24px 16px 24px; */
  /* border-bottom: 1px solid #ebeef5; */
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

/* 标签页样式 */
.info-tabs {
  width: 100%;
}

/* 标签页内容区域 */
.basic-info-content,
.password-content {
  padding: 24px 0;
}

/* 表单样式 */
.info-form,
.password-form {
  max-width: 800px;
}

/* 表单项样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
  box-shadow: 0 0 0 1px #e4e7ed inset;
}

/* 按钮样式 */
:deep(.el-button) {
  padding: 10px 20px;
  font-size: 14px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, rgba(0, 82, 217, 1) 0%, #764ba2 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  opacity: 0.9;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 82, 217, 0.3);
}

/* 标签页头部样式 */
:deep(.el-tabs__header) {
  margin-bottom: 24px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  padding: 0 24px;
  height: 48px;
  line-height: 48px;
  transition: all 0.3s;
}

:deep(.el-tabs__item:hover) {
  color: rgba(0, 82, 217, 1);
}

:deep(.el-tabs__item.is-active) {
  color: rgba(0, 82, 217, 1);
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background: rgba(0, 82, 217, 1);
  height: 3px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-info-container {
    padding: 16px;
  }

  .info-form,
  .password-form {
    max-width: 100%;
  }

  :deep(.el-col) {
    width: 100% !important;
    margin-bottom: 0;
  }
}

.page-title-container {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
